'use strict';
/* eslint no-console: 0 */
const pm2 = require('pm2');
const _ = require('lodash');
const path = require('path');
const NAME = path.basename(__dirname);
const main = path.join(__dirname, 'app');
const isWin = /^win/.test(process.platform);
const args = _.clone(process.argv);
args.splice(0, 2);

let action = args[0];
if (action && action[0] == '-')
    action = undefined;
if (!action) {
    pm2.connect(err => {
        if (err) throw err;
        pm2.describe(NAME, (err, list) => {
            const info = _.find(list, {name: NAME});
            if (info && info.pm2_env.status == 'online')
                action = 'restart';
            else action = 'start';
            pm2.disconnect();
            run();
        });
    });
} else run();

function run() {
    switch (action) {
        case 'start':
            console.log('starting %s ...', NAME);
            start();
            break;
        case 'restart':
            console.log('restarting %s ...', NAME);
            if (isWin) { // TNND, 就Windows事儿多
                pm2.connect(function() {
                    pm2.stop(NAME, function() {
                        setTimeout(function() {
                            pm2.restart(NAME, disconnect);
                        }, 100);
                    });
                });
            } else execute('restart');
            break;
        case 'stop':
            console.log('stopping %s ...', NAME);
            execute('stop');
            break;
        case 'delete':
        case 'del':
            console.log('deleting %s ...', NAME);
            execute('delete');
            break;
        case 'status':
        case 'info':
            status();
            break;
        case 'clear': // 清空日志
        case 'cls':
            flush();
            break;
        default:
            console.error('unknown action: %s', action);
            break;
    }
}

function start() {
    console.log('start', main);
    pm2.connect(() => {
        pm2.start(main, {
            name: NAME,
            scriptArgs: args
        }, disconnect);
    });
}

function disconnect() {
    pm2.disconnect();
}

function execute(action) {
    pm2.connect(() => {
        pm2[action](NAME, disconnect);
    });
}

function status() {
    pm2.connect(() => {
        pm2.describe(NAME, (err, list) => {
            console.log(list);
            pm2.disconnect();
        });
    });
}

function flush() {
    pm2.connect(() => {
        pm2.flush(disconnect);
    });
}
